package model.fshare.server;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import model.fshare.common.Command;
import model.fshare.common.CMDDelete;
import model.fshare.common.CMDGetFileList;
import model.fshare.common.FShareOperations;
import model.roomManagement.Implementation.Server;
import model.roomManagement.Interface.IDBC;

public class FShareOperator implements ServerFileShareRequestThread, FShareOperations
{
	private static FShareOperator instance = null;
	private ServerSocket serverSocket;
	
	private FShareOperator()
	{
		try 
		{
			serverSocket = new ServerSocket(5996);
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void run()
	{
		System.out.println( "====== FShareOperator: Start Running! =====" );
		
		while( true )
		{
			try
			{
				Socket socket = serverSocket.accept();
				
				ObjectInputStream oReader = new ObjectInputStream( socket.getInputStream() );
				Command command = (Command) oReader.readObject();
				Object result = command.command( this );
				
				ObjectOutputStream oWriter = new ObjectOutputStream( socket.getOutputStream() );
				oWriter.writeObject( result );
				oWriter.flush();
				
				socket.close();
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		}
	}

	@Override
	public boolean delete(int roomId, String fileName, int deleterId) 
	{
		// Call database to delete the file
		IDBC idbc = Server.getDB();
		File fileToDelete = idbc.getFile( fileName, roomId );
		if( fileToDelete != null )
		{
			return idbc.deleteFile( fileName, roomId, deleterId );
		}
		
		return true;
	}

	@Override
	public ArrayList<String> getFilesNameList(int roomId) 
	{
		// Call Service service
		IDBC idbc = Server.getDB();
		try
		{
			ArrayList<String> fileList = idbc.getFileNameList( roomId );
			
			System.out.println( "******** File Name List Output: ********" );
			for (int i = 0; i < fileList.size(); i++)
			{
				System.out.println( "The " + i + " : " + fileList.get(i) );
			}
			
			return fileList;
		}
		catch (Exception e)
		{
			return null;
		}
	}

	@Override
	public void startRunning()
	{
		Thread thread = new Thread( this );
		thread.start();
	}

	public static ServerFileShareRequestThread getInstance()
	{
		if ( instance == null )
		{
			instance = new FShareOperator();
		}
		
		return instance;
	}

}
